//
//  Controller08.swift
//  Swift30Days
//
//  Created by licheng ke on 2017/3/3.
//  Copyright © 2017年 licheng ke. All rights reserved.
//

import UIKit
import AVFoundation

//RandomColorMusic
class Controller08: UIViewController {

    var timer : Timer!
    
    var audioPlayer : AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI();
        timer = Timer(timeInterval: 0.3, target: self, selector: #selector(Controller08.randomColor), userInfo: nil, repeats: true);
        timer.fireDate = Date.distantFuture
        RunLoop.main.add(timer, forMode: .commonModes)
    }

    func configUI(){
        
        view.backgroundColor = .white;
    let gLayer = CAGradientLayer();
        gLayer.frame = view.bounds;
        gLayer.startPoint = CGPoint(x: 0.0, y: 0.0);
        gLayer.endPoint = CGPoint(x: 1.0, y: 1.0);
        gLayer.colors = [
            UIColor.white.withAlphaComponent(0.4).cgColor,
            UIColor.green.withAlphaComponent(0.2).cgColor,
            UIColor.blue.withAlphaComponent(0.3).cgColor,
            UIColor.red.withAlphaComponent(0.2).cgColor,
            UIColor.white.withAlphaComponent(0.4).cgColor
        ];
        gLayer.locations = [0.1,0.3,0.5,0.7,0.9];
        view.layer.addSublayer(gLayer);
        randomColor();
        
    let btn = UIButton(frame: CGRect(x: 0.0, y: 0, width: 148, height: 148));
        btn.addTarget(self, action: #selector(playMusic), for: .touchUpInside);
        btn.setImage(#imageLiteral(resourceName: "music play"), for: .normal);
        view.addSubview(btn);
        btn.center = view.center;
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        //判断是否能用audio

        if audioPlayer == nil {
            let url = URL(fileURLWithPath: Bundle.main.path(forResource: "Ecstasy.mp3", ofType: nil)!)
            do {
                try audioPlayer = AVAudioPlayer(contentsOf: url)
                audioPlayer?.prepareToPlay();
            } catch {
                print("\(error)")
            }
        }
    }
    
    func playMusic()  {
        
        if (audioPlayer.isPlaying) {
            audioPlayer.pause();
            timer.fireDate = Date.distantFuture
        }
        else{
            audioPlayer.play();
            timer.fireDate = Date.distantPast
        }
    
    }
    
    
    func randomColor()  {
        let redValue    = CGFloat(drand48());
        let greenValue  = CGFloat(drand48());
        let blueValue   = CGFloat(drand48());
        
        view.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1);
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    

}
